package cn.zb.controller;

import cn.zb.entity.auth.SysUser;
import cn.zb.common.util.Result;
import cn.zb.entity.auth.dto.LoginDTO;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {
    @Resource
    AuthenticationManager am;
    @Resource
    RedisTemplate<String,Object> redisTemplate;


    @RequestMapping("login")
    public Result login(@RequestBody LoginDTO dto){
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(dto.getUsername(),dto.getPassword());
        Authentication au = am.authenticate(auth);
        SysUser user = (SysUser) au.getPrincipal();
        // 生成一个token给前台
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("login:"+token,user,30, TimeUnit.MINUTES);
        // 响应用户信息
        JSONObject param = new JSONObject();
        param.put("token",token);
        param.put("username",user.getUsername());
        param.put("tx",user.getAvatar());
        param.put("nc",user.getNickName());
        return Result.data(param);
    }

}
